#pragma once
#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>              
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstring>
#include<sys/wait.h>
#include<pthread.h>
#include<functional>

#include"Log.hpp"
#include"InetAddr.hpp"
#include"ThreadPool.hpp"

const static uint16_t gport=8888;
const static int gsockfd=-1;
const static int gbacklog=8;

enum
{
    SOCKET_ERROR=1,
    BIND_ERROR,
    LISTEN_ERROR,
    ACCEPT_ERROR
};

using task_t=std::function<void()>;

class TcpServer
{
public:
    TcpServer(uint16_t port=gport,int sockfd=gsockfd):
    _port(port),
    _listensockfd(sockfd),
    _isrunning(false)
    {}
    void InitServer()
    {
        _listensockfd=::socket(AF_INET,SOCK_STREAM,0);
        if(_listensockfd<0)
        {
            LOG(FATAL,"socket create error\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO,"socket create success\n");
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));

        local.sin_family=AF_INET;
        local.sin_port=htons(_port);
        local.sin_addr.s_addr=INADDR_ANY;

        if(::bind(_listensockfd,(struct sockaddr*)&local,sizeof(local))<0)
        {
            LOG(FATAL,"bind error\n");
            exit(BIND_ERROR);
        }
        LOG(INFO,"bind success\n");

        if(::listen(_listensockfd,gbacklog)<0)
        {
            LOG(FATAL,"listen error\n");
            exit(LISTEN_ERROR);
        }
        LOG(INFO,"listen success\n");
    }
    class ThreadDate
    {
    public:
        int _sockfd;
        TcpServer* _self;
        InetAddr _addr;
    public:
        ThreadDate(int sock,TcpServer* self,InetAddr addr):_sockfd(sock),_self(self),_addr(addr){}
    };
    void Loop()
    {
        // signal(SIGCHLD,SIG_IGN);对子进程进行忽略不需要回收了，最好方案
        _isrunning=true;
        while(_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len=sizeof(client);
            int sockfd=::accept(_listensockfd,(struct sockaddr*)&client,&len);
            if(sockfd<0)
            {
                LOG(WARNING,"accept error\n");
                continue;
            }
            InetAddr addr(client);
            LOG(INFO,"get a new link client info :%s\n",addr.Ip().c_str());
            
            //多进程版本：
            // pid_t id=fork();
            // if(id==0)
            // {
            //     ::close(_listensockfd);
            //     if(fork()>0)exit(0);//创建孙子进程进行通信，子进程直接退出由父进程接收，孙子进程由OS接手
            //     Server(sockfd,addr);
            //     exit(0);
            // }
            // ::close(sockfd);
            // int n=waitpid(id,nullptr,0);
            // if(n>0)
            // {
            //     LOG(INFO,"wait child:%d success\n",id);
            
            // }

            //多线程版本
            // pthread_t tid;
            // ThreadDate* td=new ThreadDate(sockfd,this,addr);
            // pthread_create(&tid,nullptr,Execute,td);

            //线程池版本
            task_t t=std::bind(&TcpServer::Server,this,sockfd,addr);
            ThreadPool<task_t>::GetInstand()->Equeue(t);
        }

        _isrunning=false;
    }
    static void* Execute(void* args)
    {
        pthread_detach(pthread_self());
        ThreadDate* td=static_cast<ThreadDate *>(args);
        td->_self->Server(td->_sockfd,td->_addr);
        delete td;
        return nullptr;
    }
    void Server(int sockfd,struct InetAddr addr)
    {
        while(true)
        {
            char inbuff[1024];
            ssize_t n=::read(sockfd,inbuff,sizeof(inbuff)-1);
            if(n>0)
            {
                inbuff[n]=0;
                std::string echo_server="server echo :";
                echo_server+=inbuff;
                write(sockfd,echo_server.c_str(),echo_server.size());
            }
            else if(n==0)
            {
                LOG(INFO,"client %s quit\n",addr.Ip().c_str());
                break;
            }
            else
            {
                LOG(ERROR,"read error  -%s \n",addr.Ip().c_str());
                break;
            }
        }
        ::close(sockfd);
    }
    ~TcpServer()
    {}
private:
    uint16_t _port;
    int _listensockfd;
    bool _isrunning;
};